package com.caifu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.caifu.bean.Result;
import com.caifu.bean.ResultUtil;
import com.caifu.excel.ExcelMedicine;
import com.caifu.mapper.SysUserMapper;
import com.caifu.mapper.UserInfoContactMapper;
import com.caifu.mapper.YlFloorMapper;
import com.caifu.mapper.YlUserMedicineMapper;
import com.caifu.pojo.SysUser;
import com.caifu.pojo.UserInfoContact;
import com.caifu.pojo.YlFloor;
import com.caifu.pojo.YlUserMedicine;
import com.caifu.service.YlUserMedicineService;
import com.caifu.util.AesMyUtil;
import com.caifu.util.Util;
import com.caifu.vo.YlUserMedicineVo;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @author tww
 * ClassName: YlUserMedicineServiceImpl.java、
 * createTime: 2020年11月11日 13:37:14
 **/
@Service
public class YlUserMedicineServiceImpl implements YlUserMedicineService {

    @Resource
    private YlUserMedicineMapper userMedicineMapper;

    @Resource
    private YlFloorMapper ylFloorMapper;

    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private UserInfoContactMapper contactMapper;

    @Override
    public Result addUserMedicine(YlUserMedicine ylUserMedicine, SysUser user) {
        ylUserMedicine.setCreateDate(new Date());
        ylUserMedicine.setCreateTime(new Date());
        ylUserMedicine.setUpdateTime(new Date());
        ylUserMedicine.setTellerNo(String.valueOf(user.getUserNo()));
        ylUserMedicine.setStatus("1");
        userMedicineMapper.insert(ylUserMedicine);
        return ResultUtil.success(200, "success", "保存成功");
    }

    @Override
    public YlUserMedicine getUserMedicineById(String id) {
        YlUserMedicine ylUserMedicine = userMedicineMapper.selectById(id);
        SysUser user = sysUserMapper.selectById(ylUserMedicine.getTellerNo());
        if (Util.isNotNull(user)) {
            ylUserMedicine.setTellerNo(user.getUserName());
        }
        return ylUserMedicine;
    }

    @Override
    public IPage<YlUserMedicine> getUserMedicineByUserNo(String userNo, Long currentPage, Long pageSize) {
        IPage<YlUserMedicine> userMedicineIPage = userMedicineMapper.selectPage(new Page<>(currentPage, pageSize), new QueryWrapper<YlUserMedicine>()
                .eq("STATUS", 1)
                .eq("USER_NO", userNo)
                .orderByDesc("CREATE_DATE"));
        List<YlUserMedicine> records = userMedicineIPage.getRecords();
        //获取当前时间
        Date date = new Date();
        for (YlUserMedicine record : records) {
            SysUser user = sysUserMapper.selectById(record.getTellerNo());
            if (Util.isNotNull(user)) {
                record.setTellerNo(user.getUserName());
            }
            if (date.getTime() > record.getValidityDate().getTime()) {
                record.setIs_guoQi(2);
            }
          /*  if (date.getTime() > record.getUserEndDtate().getTime()) {
                record.setIs_end(2);
            }*/
        }
        return userMedicineIPage;
    }

    @Override
    public void deleteById(String id) {
        YlUserMedicine ylUserMedicine = userMedicineMapper.selectById(id);
        ylUserMedicine.setStatus("9");
        userMedicineMapper.updateById(ylUserMedicine);
    }

    @Override
    public List<List<YlUserMedicineVo>> getWarningList(String flag, String pensionNo) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("pensionNo", pensionNo);
        //1 用量预警 2 有效期预警
        String amount = "1";
        String effective = "2";
        if (amount.equals(flag)) {
            map.put("warnParam", "AND  DATEDIFF(yum.USER_END_DTATE,NOW()) BETWEEN 0 AND 7");
        } else if (effective.equals(flag)) {
            map.put("warnParam", "AND  DATEDIFF(yum.VALIDITY_DATE,NOW()) BETWEEN 0 AND 7");
        }
        List<YlUserMedicineVo> warningList = userMedicineMapper.getWarningList(map);
        return splitList(warningList, 3);
    }

    /**
     * 分割list
     *
     * @param list
     * @param groupSize
     * @return
     */
    private List<List<YlUserMedicineVo>> splitList(List<YlUserMedicineVo> list, int groupSize) {
        int length = list.size();
        // 计算可以分成多少组
        int num = (length + groupSize - 1) / groupSize;
        List<List<YlUserMedicineVo>> newList = new ArrayList<>(num);
        for (int i = 0; i < num; i++) {
            // 开始位置
            int fromIndex = i * groupSize;
            // 结束位置
            int toIndex = (i + 1) * groupSize < length ? (i + 1) * groupSize : length;
            newList.add(list.subList(fromIndex, toIndex));
        }
        return newList;
    }

    @Override
    public List<YlFloor> getFloor(String buildNo) {
        QueryWrapper<YlFloor> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("FLOOR_STATE", 1).eq("BUILDING_NO", buildNo);
        List<YlFloor> floors = ylFloorMapper.selectList(queryWrapper);
        return floors;
    }

    @Override
    public List<ExcelMedicine> getExcelData(String userNo) {
        return userMedicineMapper.getExcelData(userNo);
    }

    @Override
    public JSONObject queryAllMedicineAlertData(String type, String pensionNo) throws Exception {
        JSONObject result = new JSONObject();
        HashMap<String, Object> map = new HashMap<>();
        map.put("pensionNo", pensionNo);
        try {
            int totalSize = 0;
            JSONArray array = new JSONArray();
            //1 用量预警 2 有效期预警
            String amount = "1";
            String effective = "2";
            if (amount.equals(type)) {
                map.put("warnParam", "AND  DATEDIFF(yum.USER_END_DTATE,NOW()) BETWEEN 0 AND 7");
            } else if (effective.equals(type)) {
                map.put("warnParam", "AND  DATEDIFF(yum.VALIDITY_DATE,NOW()) BETWEEN 0 AND 7");
            }
            List<YlUserMedicineVo> warningList = userMedicineMapper.getWarningList(map);
            if (null != warningList && warningList.size() > 0) {
                totalSize = warningList.size();
                for (YlUserMedicineVo m : warningList
                ) {
                    if (null != m) {
                        JSONObject obj = new JSONObject();
                        obj.put("name", m.getUserName());
                        obj.put("pensionAddress", m.getBuild() + "-" + m.getRoom() + "-" + m.getBed());
                        //查询紧急联系人
                        QueryWrapper<UserInfoContact> contractQueryWrapper = new QueryWrapper<>();
                        contractQueryWrapper.eq("user_no", m.getUserNo());
                        List<UserInfoContact> contactList = contactMapper.selectList(contractQueryWrapper);
                        String linkInfo = "";
                        if (null != contactList && contactList.size() > 0) {
                            UserInfoContact c = contactList.get(0);
                            if (null != c) {
                                linkInfo = "紧急联系人：" + c.getContactName() + " " + AesMyUtil.Decrypt(c.getMobile());
                            }
                        }
                        obj.put("linkInfo", linkInfo); //紧急联系人
                        obj.put("medicineName", m.getMeicineName()); //药名
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        String endDate = sdf.format(m.getUserEndDtate());
                        String validDate = sdf.format(m.getValidityDate());
                        obj.put("endDate", endDate);
                        obj.put("validDate", validDate);
                        obj.put("endRemain", m.getEndRemain());
                        obj.put("validRemain", m.getValidRemain());
                        array.add(obj);
                    }
                }
            }
            result.put("code", "0000");
            result.put("codeDesc", "查询成功");
            result.put("totalSize", totalSize);
            result.put("array", array);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", "0000");
            result.put("codeDesc", "查询失败");
            result.put("totalSize", 0);
            return result;
        }
    }
}
